import global from "@/api/global.js"

const upload = async (num, type,url) => {// 单图上传 single  多图上传 more
	var _this = this;
	let baseUrl = global.baseUrl; // baseUrl需要引入，可以在封装的请求方法中获取
	return new Promise((resolve, reject) => {
		if(num == "more"){
			uni.chooseImage({
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], //从相册选择
				success: (res) => {
					uni.showLoading();
					const tempFilePaths = res.tempFilePaths;
					const uploads = [];
					const uploadsPreview = [];
					const uploadsId = [];
					tempFilePaths.forEach((value, index) => {
						uploads.push(value);
					});
					uploads.forEach((item, index) => {
						console.log(item)
						uni.uploadFile({
							url: baseUrl + url,
							filePath: item,
							name: 'file',
							// header: {
							// 	"token": uni.getStorageSync('token'),
							// 	"uid": uni.getStorageSync('uid')
							// },
							//header:{"Content-Type": "multipart/form-data"},
							formData:{ 
								token: uni.getStorageSync('token'),
								},
							success: r => {
								uploadsPreview.push({
									path:JSON.parse(r.data).path,
									id:JSON.parse(r.data).id
								});
								if(uploadsPreview.length == uploads.length){
									resolve(uploadsPreview);
								}
								uni.hideLoading();
							},
							fail: (err) => {
								uni.hideLoading();
								console.log(JSON.stringify(err))
							}
							
						});
					});
				},
				fail: (err) => {
					uni.hideLoading();
					console.log(JSON.stringify(err));
				}
			});
		}else{
			// uni.chooseImage({
			// 	count: 1,
			// 	sizeType: ['original', 'compressed'],
			// 	sourceType: ['album', 'camera'],
			//     success: (chooseImageRes) => {
			//         const tempFilePaths = chooseImageRes.tempFilePaths;
			//         uni.uploadFile({
			//             url: baseUrl + url, //仅为示例，非真实的接口地址
			//             filePath: tempFilePaths[0],
			//             name: 'file',
			//             formData: {
			//                 _token: uni.getStorageSync('token'),
			//             },
			//             success: (uploadFileRes) => {
			//                 console.log(uploadFileRes.data);
			// 				let imgData = JSON.parse(uploadFileRes.data)
			// 				imgData.showImg = chooseImageRes.tempFilePaths[0]
			// 				resolve(imgData);
			// 				uni.hideLoading();
			//             }
			//         });
			//     }
			// });
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: res => {
					let ur = baseUrl + url
					console.log('res',res,)
					uni.showLoading();
					uni.uploadFile({
						url:baseUrl + url,
						filePath: res.tempFilePaths[0],
						name: 'file',
						formData:{ 
								token: uni.getStorageSync('token'),
							},
						success: r => {
							let imgData = JSON.parse(r.data)
							imgData.showImg = res.tempFilePaths[0]
							resolve(imgData);
							uni.hideLoading();
						}
					});
				},
				fail: (err) => {
					uni.hideLoading();
					console.log(JSON.stringify(err));
				}
			})
		}
	})
}
// 调用方式：
// 1、在main.js中引入工具类import tool from '@/tool/tool'
// 2、在main.js中注册：Vue.prototype.$upload = tool.upload
// 3、页面调用：this.$upload().then(res => {
//              res为上传接口返回数据
//            })
//统一提示方便全局修改
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
// 获取地址栏中某个key的值，如果没有key，返回false
const getQueryVariable = (key, url) => {
	var query = url.split('?')[1];
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == key) {
			return pair[1];
		}
	}
	return (false);
}
// 对象转get拼接参数
const objParseParam = (obj) => {
	let paramsStr = '';
	if (obj instanceof Array) return paramsStr;
	if (!(obj instanceof Object)) return paramsStr;
	for (let key in obj) {
		paramsStr += `${key}=${obj[key]}&`;
	}
	return paramsStr.substring(0, paramsStr.length - 1);
}
// 复制
const h5Copy = (content) => {
	//#ifdef APP-PLUS
		uni.setClipboardData({
			data: content,
			success: function () {
				uni.showToast({icon:'none',title:'复制成功'})
			},
			fail: function () {
				uni.showToast({icon:'none',title:'复制失败'})
			}
		});
	//#endif
	//#ifdef MP-WEIXIN
		uni.setClipboardData({
			data: content,
			success: function () {
				uni.showToast({icon:'none',title:'复制成功'})
			},
			fail: function () {
				uni.showToast({icon:'none',title:'复制失败'})
			}
		});
	//#endif
	//#ifndef APP-PLUS || MP-WEIXIN
		let textarea = document.createElement('textarea');
		textarea.value = content;
		textarea.readOnly = 'readOnly';
		document.body.appendChild(textarea);
		textarea.select(); // 选择对象
		if(content){
			textarea.setSelectionRange(0, content.length); //核心
		}else{
			textarea.setSelectionRange(0, ''); //核心
		}
		let result = document.execCommand('Copy'); // 执行浏览器复制命令
		textarea.remove();
		const msg = result ? '复制成功' : '复制失败';
		uni.showToast({icon:'none',title:msg})
	//#endif
}
// 保存图片
const savePic = (url) => {
	//#ifdef APP-PLUS
		plus.gallery.save(url, function () {
			uni.showToast({icon:'none',title:'保存图片成功'});
		},function(){
			uni.showToast({icon:'none',title:'保存失败'})
		});
	//#endif
	
	//#ifdef H5
		var a = document.createElement('a');
		a.href = url;
		a.download = new Date().getTime();
		a.click();
	//#endif
}
// 图片预览
const preview = (picArr, current) => {
	uni.previewImage({
		current:current || 0,
		urls: picArr,
		indicator:"number"
	});
}
// 数据分层
const sortData = (oArr, length) => {
	let arr = [];
	let minArr = [];
	oArr.forEach(c => {
		if (minArr.length === length) {
			minArr = [];
		}
		if (minArr.length === 0) {
			arr.push(minArr);
		}
		minArr.push(c);
	});
	return arr;
}
//获取路径后面的参数
const getUrlParam = (name) => {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
	let url = window.location.href.split('#')[0]
	let search = url.split('?')[1]
	if (search) {
		var r = search.substr(0).match(reg)
		if (r !== null) return unescape(r[2])
			return null
	} else {
		return null
	}
}
// 节流函数
const delay = (()=> {
	let timer = 0;
	return function(callback, ms) {
		clearTimeout(timer);
		timer = setTimeout(callback, ms);
	 };
})();

export default {
	upload,
	msg,
	getQueryVariable,
	objParseParam,
	h5Copy,
	savePic,
	preview,
	sortData,
	getUrlParam,
	delay
}
